package com.wenbing.miio.core;

import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;

/**
 * 基于DatagramSocket实现的NetworkInterface
 *
 * @author wen bing
 * @projectName: miio
 * @package: com.wenbing.miio.core
 * @className: DataAdapter
 * @date 2024/09/21 12:41
 **/
public class DatagramSocketNetworkInterface implements NetworkInterface {
    private DatagramSocket socket;

    public DatagramSocketNetworkInterface() throws SocketException {
        this(0);
    }

    public DatagramSocketNetworkInterface(int port) throws SocketException {
        this(new InetSocketAddress("0.0.0.0", port));
    }

    public DatagramSocketNetworkInterface(InetSocketAddress address) throws SocketException {
        this.socket = new DatagramSocket(address);
    }

    @Override
    public void boot() {

    }

    @Override
    public SocketAddress getAddress() {
        return this.socket.getLocalSocketAddress();
    }

    @Override
    public RowFrame receiveRowFrame() throws IOException {
        DatagramPacket pkg = new DatagramPacket(new byte[512], 512);
        socket.receive(pkg);
        NetworkLayerContext c = MapNetworkLayerContext.rootContext(getAddress(), pkg.getSocketAddress());
        return new RowFrame(c, ByteBuffer.wrap(pkg.getData(), pkg.getOffset(), pkg.getLength()));
    }

    @Override
    public void sendRowFrame(RowFrame rowFrame) throws IOException {
        ByteBuffer bf = rowFrame.getByteBuffer();
        SocketAddress address = rowFrame.getContext().getShareAttribute(MapNetworkLayerContext.REMOTE_ADDRESS);
        int offset = bf.arrayOffset();
        DatagramPacket pkg = new DatagramPacket(bf.array(),offset + bf.position(), bf.limit(), address);
        socket.send(pkg);
    }
}
